package com.ukao.cashregister.ui.orderQuiry;


import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RatingBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.gprinterio.GpDevice;
import com.mcxtzhang.commonadapter.rv.OnItemClickListener;
import com.ukao.cashregister.R;
import com.ukao.cashregister.adapter.OperationStatusAdapter;
import com.ukao.cashregister.adapter.OrdersDetailAdapter;
import com.ukao.cashregister.adapter.OrdersStateAdapter;
import com.ukao.cashregister.base.MvpFragment;
import com.ukao.cashregister.bean.AllMarkprintBean;
import com.ukao.cashregister.bean.ClothginQuiryBean;
import com.ukao.cashregister.bean.OrderStateBean;
import com.ukao.cashregister.bean.PayInfoBean;
import com.ukao.cashregister.bean.QueryPaBean;
import com.ukao.cashregister.bean.QuiryDetailBean;
import com.ukao.cashregister.bean.ReceiptBean;
import com.ukao.cashregister.bean.RefundMethodBean;
import com.ukao.cashregister.bean.SendModeBean;
import com.ukao.cashregister.bean.UserInfoBean;
import com.ukao.cashregister.consts.Constant;
import com.ukao.cashregister.dialog.BackWashDialogFragment;
import com.ukao.cashregister.dialog.BatchDialogFragment;
import com.ukao.cashregister.dialog.CrippledDialogFragment;
import com.ukao.cashregister.dialog.InquiryDialogFragment;
import com.ukao.cashregister.bean.RefundRecordBean;
import com.ukao.cashregister.dialog.RefundPayDialogFragment;
import com.ukao.cashregister.dialog.RefundRecordDialogFragment;
import com.ukao.cashregister.dialog.SendModeDialogFragment;
import com.ukao.cashregister.dialog.TansNoDialogFragment;
import com.ukao.cashregister.eventbus.AppEvent;
import com.ukao.cashregister.eventbus.PayEvent;
import com.ukao.cashregister.listener.MyOnItemClickListener;
import com.ukao.cashregister.listener.OnDialogSureClickListener;
import com.ukao.cashregister.listener.OnItemChildClickListener;
import com.ukao.cashregister.pesenter.QuiryDetailPesenter;
import com.ukao.cashregister.printer.PrintMiuiHelper;
import com.ukao.cashregister.printer.PrinterHelper;
import com.ukao.cashregister.printer.PrinterReceipt;
import com.ukao.cashregister.ui.MainActivity;
import com.ukao.cashregister.ui.clothinQuery.ClothingDetailsFragment;
import com.ukao.cashregister.ui.stokin.GatheringFragment;
import com.ukao.cashregister.utils.CheckUsbDeviceUtils;
import com.ukao.cashregister.utils.CheckUtils;
import com.ukao.cashregister.utils.ImageUtils;
import com.ukao.cashregister.utils.MyDateUtils;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.view.QuiryDetailView;
import com.ukao.cashregister.widget.DividerDecoration;
import com.ukao.cashregister.widget.ShapedImageView;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.ukao.cashregister.R.id.gathering_btn;
import static com.ukao.cashregister.R.id.marking_btn;
import static com.ukao.cashregister.R.id.orders_detail_back_to_wash;


/**
 * 订单详情列表
 */
public class OrderQuiryDetailFragment extends MvpFragment<QuiryDetailPesenter> implements QuiryDetailView{

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    Unbinder unbinder;
    OrdersDetailAdapter mAdapter;
    OperationStatusAdapter mOperationAdapter;
    List<QuiryDetailBean.ProductListBean> items = new ArrayList<>();
    List<QuiryDetailBean.StatusListBean> operations = new ArrayList<>();


    @BindView(R.id.refund_btn)
   Button refundBtn;
    @BindView(R.id.include_part3)
    LinearLayout includePart3;
    @BindView(R.id.back)
    TextView back;
    @BindView(R.id.order_detail_tab1)
    RadioButton orderDetailTab1;
    @BindView(R.id.order_detail_tab2)
    RadioButton orderDetailTab2;
    @BindView(R.id.order_detail_tab3)
    RadioButton orderDetailTab3;
    @BindView(R.id.order_detail_tab4)
    RadioButton orderDetailTab4;
    @BindView(R.id.order_detail_tab5)
    RadioButton orderDetailTab5;
    @BindView(R.id.order_detail_tab6)
    RadioButton orderDetailTab6;
    @BindView(R.id.order_detail_tab7)
    RadioButton orderDetailTab7;
    @BindView(R.id.order_detail_tab8)
    RadioButton orderDetailTab8;
    @BindView(R.id.order_detail_group)
    RadioGroup orderDetailGroup;
    @BindView(R.id.state_recycler)
    RecyclerView stateRecycler;
    @BindView(R.id.order_quiry_one)
    View orderQuiryOne;
    @BindView(R.id.originText)
    TextView originText;
    @BindView(R.id.createTime)
    TextView createTime;
    @BindView(R.id.orderNo)
    TextView orderNo;
    @BindView(R.id.transNo)
    TextView transNo;
    @BindView(R.id.factoryTransNo)
    TextView factoryTransNo;
    @BindView(R.id.statusText)
    TextView statusText;
    @BindView(R.id.order_quiry_two)
    View orderQuiryTwo;
    @BindView(R.id.paymentPrice)
    TextView paymentPrice;
    @BindView(R.id.payStatusText)
    TextView payStatusText;

    @BindView(R.id.paidPrice)
    TextView paidPrice;
    @BindView(R.id.refundPrice)
    TextView refundPrice;
    @BindView(R.id.refund_status)
    TextView refundStatus ;
    @BindView(R.id.user_info_icon)
    ShapedImageView userInfoIcon;
    @BindView(R.id.user_info_name)
    TextView userInfoName;
    @BindView(R.id.user_info_wechat_name)
    TextView userInfoWechatName;
    @BindView(R.id.wxId)
    ImageView wxId;
    @BindView(R.id.phone)
    ImageView phone;
    @BindView(R.id.verifyAndriod)
    ImageView verifyAndriod;
    @BindView(R.id.verifyIos)
    ImageView verifyIos;
    @BindView(R.id.verifyPhone)
    ImageView verifyPhone;
    @BindView(R.id.user_info_subscribe)
    TextView userInfoSubscribe;
    @BindView(R.id.user_info_phone_account)
    TextView userInfoPhoneAccount;
    @BindView(R.id.user_info_vip_card_no)
    TextView userInfoVipCardNo;
    @BindView(R.id.user_info_part5_vip_levels_tv)
    TextView userInfoPart5VipLevelsTv;
    @BindView(R.id.user_info_part5_vip_discount)
    TextView userInfoPart5VipDiscount;
    @BindView(R.id.user_info_balance)
    TextView userInfoBalance;
    @BindView(R.id.user_info_credits)
    TextView userInfoCredits;
    @BindView(R.id.user_info_part6_tag1)
    TextView userInfoPart6Tag1;
    @BindView(R.id.user_info_part6_tag2)
    TextView userInfoPart6Tag2;
    @BindView(R.id.user_info_part6_tag3)
    TextView userInfoPart6Tag3;
    @BindView(R.id.orders_detail_pick_clothing)
    Button ordersDetailPickClothing;
    @BindView(orders_detail_back_to_wash)
    Button ordersDetailBackToWash;
    @BindView(R.id.orders_detail_recycler)
    RecyclerView ordersDetailRecycler;
    @BindView(R.id.order_quiry_three)
    View orderQuiryThree;
    @BindView(R.id.order_quiry_four)
    View orderQuiryFour;
    @BindView(R.id.takeModeText)
    TextView takeModeText;
    @BindView(R.id.takeDate)
    TextView takeDate;
    @BindView(R.id.actualTakeTime)
    TextView actualTakeTime;
    @BindView(R.id.takeName)
    TextView takeName;
    @BindView(R.id.takePhone)
    TextView takePhone;
    @BindView(R.id.order_detail_create_orders_get_person_layout)
    LinearLayout orderDetailCreateOrdersGetPersonLayout;
    @BindView(R.id.takeAddress)
    TextView takeAddress;
    @BindView(R.id.order_detail_create_orders_get_address_layout)
    LinearLayout orderDetailCreateOrdersGetAddressLayout;
    @BindView(R.id.takeWorkImg)
    ShapedImageView takeWorkImg;
    @BindView(R.id.takeWorkName)
    TextView takeWorkName;
    @BindView(R.id.takeWorkPhone)
    TextView takeWorkPhone;
    @BindView(R.id.sendModeText)
    TextView sendModeText;
    @BindView(R.id.send_date)
    TextView sendDate;
    @BindView(R.id.actualSendTime)
    TextView actualSendTime;
    @BindView(R.id.sendName)
    TextView sendName;
    @BindView(R.id.sendPhone)
    TextView sendPhone;
    @BindView(R.id.order_detail_create_orders_delivery_person_layout)
    LinearLayout orderDetailCreateOrdersDeliveryPersonLayout;
    @BindView(R.id.sendAddress)
    TextView sendAddress;
    @BindView(R.id.order_detail_create_orders_delivery_address_layout)
    LinearLayout orderDetailCreateOrdersDeliveryAddressLayout;
    @BindView(R.id.sendWorkImg)
    ShapedImageView sendWorkImg;
    @BindView(R.id.sendWorkName)
    TextView sendWorkName;
    @BindView(R.id.sendWorkPhone)
    TextView sendWorkPhone;
    @BindView(R.id.order_quiry_five)
    View orderQuiryFive;
    @BindView(R.id.transNo_btn)
    Button transNoBtn;

    @BindView(R.id.operation_status_recycler)
    RecyclerView operationStatusRecycler;
    @BindView(R.id.order_quiry_six)
    View orderQuirySix;
    @BindView(R.id.userRemark)
    TextView userRemark;
    @BindView(R.id.remark)
    TextView remark;
    @BindView(R.id.order_quiry_seven)
    View orderQuirySeven;
    @BindView(R.id.servicePoints_ratingBar)
    RatingBar servicePointsRatingBar;
    @BindView(R.id.servicePoints)
    TextView servicePoints;
    @BindView(R.id.serviceEvaluate)
    TextView serviceEvaluate;
    @BindView(R.id.workPoints_ratingBar)
    RatingBar workPointsRatingBar;
    @BindView(R.id.workPoints)
    TextView workPoints;
    @BindView(R.id.workEvaluate)
    TextView workEvaluate;
    @BindView(R.id.scroll_view)
    ScrollView scrollView;
    @BindView(R.id.image_state)
    ImageView imageState;
    @BindView(R.id.payMethodText)
    TextView payMethodText;
    @BindView(R.id.pay_time)
    TextView payTime;
    @BindView(R.id.couponAmt)
    TextView couponAmt;
    @BindView(R.id.sign_btn)
    Button signBtn;
    @BindView(R.id.accomplish_btn)
    Button accomplishBtn;
    @BindView(R.id.sex)
    TextView sex;
    @BindView(R.id.printers_btn)
    Button printersBtn;
    @BindView(R.id.marking_btn)
    Button markingBtn;
    @BindView(R.id.reashing_btn)
    Button reashingBtn;
    @BindView(R.id.cancellation_btn)
    Button cancellationBtn;
    @BindView(R.id.gathering_btn)
   Button gatheringBtn;
    @BindView(R.id.tv_union_name)
    TextView  tvUnionName;


    private ArrayList<SendModeBean> mSendModeBean;

    private String timetype = "yyyy/MM/dd HH:mm:ss";
    private String mParam1;
    private String mParam2;
    private OrdersStateAdapter mOrdersStateAdapter;
    private List<OrderStateBean> mOrderStateData = new ArrayList<>();
    private String mOrderId;
    private ArrayList<QuiryDetailBean.ProductListBean> takeClogthData = new ArrayList<QuiryDetailBean.ProductListBean>(); /*记录取衣的集合*/
    private String backtitle;

    private boolean isEnableChangeSendMode;
    private InquiryDialogFragment mInquiryDialog;
    private String moveproductIds;
    private QuiryDetailBean mQuiryDetailBean;
    private String orderProIds;
    private ArrayList<QueryPaBean> mQuerypayData;
    private ArrayList<RefundMethodBean> mRefundMethodBean;
    private boolean isOrederRefund;

    public static OrderQuiryDetailFragment newInstance(String param1, String param2) {
        OrderQuiryDetailFragment fragment = new OrderQuiryDetailFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mOrderId = getArguments().getString(ARG_PARAM1);
            backtitle = getArguments().getString(ARG_PARAM2);
        }


    }

    @Override
    protected QuiryDetailPesenter createPresenter() {
        return new QuiryDetailPesenter(this);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_order_quiry_detail, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        initListener();
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        refreshData();
    }

    private void refreshData() {
        mvpPresenter.qrderQuiryDetailsData(_mActivity, mOrderId);
        mvpPresenter.orderStatusprogress(mOrderId);
        mvpPresenter.queryPayList(mOrderId);
    }

    @Override
    protected void initView() {
        back.setText(backtitle);
        mOrdersStateAdapter = new OrdersStateAdapter(activity, mOrderStateData);
        stateRecycler.setLayoutManager(new GridLayoutManager(activity, 5));
        stateRecycler.setAdapter(mOrdersStateAdapter);
        stateRecycler.setNestedScrollingEnabled(false);

        mAdapter = new OrdersDetailAdapter(activity, items);
        ordersDetailRecycler.setLayoutManager(new LinearLayoutManager(activity));
        ordersDetailRecycler.addItemDecoration(new DividerDecoration(getActivity(), DividerDecoration.VERTICAL_LIST));
        ordersDetailRecycler.setAdapter(mAdapter);
        ordersDetailRecycler.setNestedScrollingEnabled(false);

        mOperationAdapter = new OperationStatusAdapter(activity, operations);
        operationStatusRecycler.setLayoutManager(new LinearLayoutManager(activity));
        operationStatusRecycler.setAdapter(mOperationAdapter);
        operationStatusRecycler.setNestedScrollingEnabled(false);
    }

    @Override
    protected void initListener() {
        super.initListener();
        mAdapter.setOnItemClickListener(mOnItemClickListener);
        mAdapter.setOnItemChildClickListener(mOnItemChildClick);

    }

    private OnItemChildClickListener mOnItemChildClick = new OnItemChildClickListener() {
        @Override
        public void onChildItemClick(int id, int pos) {
            QuiryDetailBean.ProductListBean mItem = mAdapter.getItem(pos);
            if (mItem==null)return;
            mvpPresenter.clothginQuirydetail(_mActivity, mItem.getScanCode());
        }
    };


    private OnItemClickListener mOnItemClickListener = new MyOnItemClickListener() {
        @Override
        public void onItemClick(ViewGroup viewGroup, View view, Object o, int i) {
            super.onItemClick(viewGroup, view, o, i);
            QuiryDetailBean.ProductListBean mItem = (QuiryDetailBean.ProductListBean) o;
            if (!mItem.isEnableSign() && !mItem.isEnableStockRework()&&! mItem.isEnableRefund())
                return;

            mItem.setCheck(!mItem.isCheck());
            mAdapter.notifyDataSetChanged();
            isShowTakeClothingBtn(mAdapter.getDatas());


        }
    };

    @OnCheckedChanged({R.id.order_detail_tab1, R.id.order_detail_tab2, R.id.order_detail_tab3, R.id.order_detail_tab4, R.id.order_detail_tab5, R.id.order_detail_tab6, R.id.order_detail_tab7, R.id.order_detail_tab8})
    public void OnCheckedChanged(CompoundButton view, boolean check) {
        if (check)
            switch (view.getId()) {
                case R.id.order_detail_tab1:
                    Constant.scrollToView(scrollView, orderQuiryOne);
                    break;
                case R.id.order_detail_tab2:
                    Constant.scrollToView(scrollView, orderQuiryTwo);
                    break;
                case R.id.order_detail_tab3:
                    Constant.scrollToView(scrollView, orderQuiryThree);
                    break;
                case R.id.order_detail_tab4:
                    Constant.scrollToView(scrollView, orderQuiryFour);
                    break;
                case R.id.order_detail_tab5:
                    Constant.scrollToView(scrollView, orderQuiryFive);
                    break;
                case R.id.order_detail_tab6:
                    Constant.scrollToView(scrollView, orderQuirySix);
                    break;
                case R.id.order_detail_tab7:
                    Constant.scrollToView(scrollView, orderQuirySeven);
                    break;
                case R.id.order_detail_tab8:
                    Constant.scrollToView(scrollView, orderQuirySeven);
                    break;
            }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        if (!CheckUtils.isNull(PrinterHelper.getInstance())) {
            PrinterHelper.getInstance().onDestroy();
        }
    }

    @Override
    public void getDataSuccess(QuiryDetailBean model) {
        this.mQuiryDetailBean = model;
        if(ordersDetailPickClothing.getVisibility() ==View.VISIBLE){
            ordersDetailPickClothing.setVisibility(View.GONE );
        }
        if(reashingBtn.getVisibility() ==View.VISIBLE){
            reashingBtn.setVisibility(View.GONE );
        }
        if(ordersDetailBackToWash.getVisibility() ==View.VISIBLE){
            ordersDetailBackToWash.setVisibility(View.GONE );
        }


        cancellationBtn.setVisibility(model.isEnableDestroy() ? View.VISIBLE : View.GONE);/*作废*/
        QuiryDetailBean.UserInfoBean useInfo = model.getUserInfo();

        userInfoName.setText(useInfo.getName());/*用户名*/
        //设置是不是团体客服
        if(!TextUtils.isEmpty(useInfo.getUnionName())){
            tvUnionName.setVisibility(View.VISIBLE);
            tvUnionName.setText(useInfo.getUnionName());
        }else {
            tvUnionName.setText("");
            tvUnionName.setVisibility(View.INVISIBLE);
        }
        if (model.isCanceled()) {/*是否取消*/
            imageState.setImageResource(R.drawable.order_no_sign);
        }
        isEnableChangeSendMode = model.isEnableChangeSendMode();
        if (model.isEnableChangeSendMode()) {
            Drawable rightDrawable = getResources().getDrawable(R.drawable.blue_down);
            rightDrawable.setBounds(0, 0, rightDrawable.getMinimumWidth(), rightDrawable.getMinimumHeight());
            sendModeText.setCompoundDrawables(null, null, rightDrawable, null);
        } else {
            sendModeText.setTextColor(resources.getColor(R.color.black));
            sendModeText.setCompoundDrawables(null, null, null, null);
        }


        switch(model.getRefundStatus()) {
            case 1:
                refundStatus.setVisibility(View.VISIBLE);
                refundStatus.setText("已退款");

                break;
            case 2:
                refundStatus.setVisibility(View.VISIBLE);
                refundStatus.setText("部分退款");

                break;
            default:
                if (model.getRefundPrice()>0){
                    refundStatus.setVisibility(View.VISIBLE);
                    refundStatus.setText("");

                }

                break;
        }



        sex.setText(useInfo.getSex());
        signBtn.setVisibility(model.isEnableSign() ? View.VISIBLE : View.GONE);/*签收*/
        accomplishBtn.setVisibility(model.isEnableComplete() ? View.VISIBLE : View.GONE);/*完成*/
        refundBtn.setVisibility(model.isEnableRefund() ? View.VISIBLE : View.INVISIBLE);/*退款*/
        gatheringBtn.setVisibility(model.isEnablePay() ? View.VISIBLE : View.INVISIBLE);
        verifyPhone.setVisibility(useInfo.getVerifyPhone() == 1 ? View.VISIBLE : View.GONE);
        verifyAndriod.setVisibility(useInfo.getVerifyAndriod() == 1 ? View.VISIBLE : View.GONE);
        verifyIos.setVisibility(useInfo.getVerifyIos() == 1 ? View.VISIBLE : View.GONE);
        ImageUtils.loadImage(_mActivity, useInfo.getHeadimgPath(), userInfoIcon);
        userInfoPhoneAccount.setText(!CheckUtils.isEmpty(useInfo.getPhone()) == true ? useInfo.getPhone() : "");/*手机*/
        userInfoSubscribe.setVisibility(useInfo.getSubscribe() == -1 ? (View.VISIBLE) : (View.GONE)); /*微信已跑路*/
        wxId.setVisibility(CheckUtils.isNull(useInfo.getWxId()) ? View.GONE : useInfo.getWxId() == 1 ? View.VISIBLE : View.GONE);

        phone.setVisibility(!CheckUtils.isEmpty(useInfo.getPhone()) == true ? (View.VISIBLE) : (View.GONE));
        verifyPhone.setVisibility(useInfo.getVerifyPhone() == 1 ? (View.VISIBLE) : (View.GONE));
        verifyAndriod.setVisibility(useInfo.getVerifyAndriod() == 1 ? (View.VISIBLE) : (View.GONE));
        verifyIos.setVisibility(useInfo.getVerifyIos() == 1 ? (View.VISIBLE) : (View.GONE));
        userInfoWechatName.setText(CheckUtils.isEmpty(useInfo.getWxNickname()) == true ? "" : "微信昵称：" + useInfo.getWxNickname());
        ImageUtils.loadImage(_mActivity, useInfo.getHeadimgPath(), userInfoIcon);
        userInfoCredits.setText(useInfo.getPoint() + "");  /* 积分*/
        userInfoBalance.setText(CheckUtils.isEmptyNumber(useInfo.getBalance()) + "元");
        userInfoVipCardNo.setText(!CheckUtils.isEmpty(useInfo.getCardNo()) ? useInfo.getCardNo() : "");  /*卡号*/

        String  cardName="";
        if (CheckUtils.isEmpty(   model.getCardName())){
            cardName=CheckUtils.isEmptyString(useInfo.getCardName());
        }else{
            cardName=CheckUtils.isEmptyString(model.getCardName());
        }
        String  cardDiscount="";
        if (!CheckUtils.isEmpty(model.getDiscountDesc())){
            cardDiscount="多折扣";
        }else if (!CheckUtils.isNull(model.getDiscount())){
            cardDiscount=CheckUtils.isDiscount(model.getDiscount(),1);
        }else {
            cardDiscount=useInfo.getCardDiscount();
        }

        userInfoPart5VipDiscount.setText(cardDiscount);
        userInfoPart5VipLevelsTv.setText(cardName);  /*等级*/
        couponAmt.setText(CheckUtils.isEmptyNumber(model.getCouponAmt()));/*优惠券*/
        takeModeText.setText(CheckUtils.isEmptyString(model.getTakeModeText()));/*上门取件*/
        takeName.setText(CheckUtils.isEmptyString(model.getTakeName()));/*取件联系人*/
        takePhone.setText(CheckUtils.isEmptyString(model.getTakePhone()));/*取件联系人*/
        takeAddress.setText(CheckUtils.isEmptyString(model.getTakeAddress()));
        ImageUtils.loadImage(_mActivity, model.getTakeWorkImg(), takeWorkImg);
        takeWorkPhone.setText(CheckUtils.isEmptyString(model.getTakeWorkPhone()));
        takeWorkName.setText(CheckUtils.isEmptyString(model.getTakeWorkName()));
        sendName.setText(CheckUtils.isEmptyString(model.getSendName()));
        sendPhone.setText(CheckUtils.isEmptyString(model.getSendPhone()));
        sendAddress.setText(CheckUtils.isEmptyString(model.getSendAddress()));
        sendWorkName.setText(CheckUtils.isEmptyString(model.getSendWorkName()));
        sendWorkPhone.setText(CheckUtils.isEmptyString(model.getSendWorkPhone()));
        ImageUtils.loadImage(_mActivity, model.getSendWorkImg(), sendWorkImg);
        userRemark.setText(CheckUtils.isEmptyString(model.getUserRemark()));
        remark.setText(CheckUtils.isEmptyString(model.getRemark()));
        sendModeText.setText(CheckUtils.isEmptyString(model.getSendModeText()));
        originText.setText(CheckUtils.isEmptyString(model.getOriginText()));
        createTime.setText(CheckUtils.isEmptyString(MyDateUtils.formatDateCustom(model.getCreateTime(), timetype)));
        orderNo.setText(CheckUtils.isEmptyString(model.getOrderNo()));
        transNo.setText(CheckUtils.isEmpty(model.getTransNo())?"":"运单号："+model.getTransNo());
        factoryTransNo.setText(CheckUtils.isEmpty(model.getFactoryTransNo())?"":"工厂运单号："+model.getFactoryTransNo());
        transNoBtn.setText(CheckUtils.isEmpty(model.getFactoryTransNo())?getString(R.string.waybill_number)
                :getString(R.string.modified_number)); /*工厂运单号*/
        transNoBtn.setVisibility(model.isEnableUpdateFactoryTransNo() ? View.VISIBLE : View.GONE);
        statusText.setText(CheckUtils.isEmptyString(model.getStatusText()));
        printersBtn.setVisibility(model.isEnablePrint() ? View.VISIBLE : View.GONE);
        paymentPrice.setText(CheckUtils.isEmptyNumber(model.getPayablePrice()));
        paidPrice.setText(CheckUtils.isEmptyNumber(model.getPaidPrice()) + "");
        refundPrice.setText(CheckUtils.isEmptyNumber(model.getRefundPrice()) + "");
        payStatusText.setText(CheckUtils.isEmptyString(model.getPayStatusText()));
        if (CheckUtils.isEmpty(model.getStatusList())) {/*物流信息*/
            operationStatusRecycler.setVisibility(View.GONE);
        } else {
            mOperationAdapter.setDatas(model.getStatusList());
        }


        List<QuiryDetailBean.ProductListBean> mproductList = model.getProductList();
        if (!CheckUtils.isEmpty(mproductList)) {
            mAdapter.setDatas(mproductList);
            int markCount = 0;
            for (QuiryDetailBean.ProductListBean productListBean : mproductList) {
                if (productListBean.isEnablePrint()) {
                    markCount = markCount + 1;
                }
            }

            if (markCount == mproductList.size()) {
                markingBtn.setVisibility(View.VISIBLE);
            } else if (markingBtn.getVisibility() == View.VISIBLE) {
                markingBtn.setVisibility(View.GONE);
            }


        } else {
            if (markingBtn.getVisibility() == View.VISIBLE) markingBtn.setVisibility(View.GONE);
            includePart3.setVisibility(View.INVISIBLE);
        }




          /*payStatus0	未支付1	已支付*/
        if (!model.getPayStatus()) {

            payStatusText.setTextColor(resources.getColor(R.color.warm_red));
            paymentPrice.setTextColor(resources.getColor(R.color.warm_red));
        }else{

                payStatusText.setTextColor(resources.getColor(R.color.green));
                paymentPrice.setTextColor(resources.getColor(R.color.green));

        }

        if (!CheckUtils.isEmpty(model.getEvaluateList())) {
            QuiryDetailBean.evaluateListBean mevaluateList = model.getEvaluateList().get(0);
            servicePointsRatingBar.setRating(mevaluateList.getServicePoints());
            workPointsRatingBar.setRating(mevaluateList.getWorkPoints());
            workPoints.setText(mevaluateList.getWorkPoints() + "");
            servicePoints.setText(mevaluateList.getServicePoints() + "");
            workEvaluate.setText(CheckUtils.isEmptyString(mevaluateList.getWorkEvaluate()));
            serviceEvaluate.setText(CheckUtils.isEmptyString(mevaluateList.getServiceEvaluate()));
        }
        ordersDetailPickClothing.setVisibility(View.GONE);
        reashingBtn.setVisibility(View.GONE);
        takeDate.setText(model.getTake_date() + model.getTake_time_start() + model.getTake_time_end());
        sendDate.setText(CheckUtils.isEmptyString(model.getSendDate()) +model.getSend_time_start() +model.getSend_time_end());
        actualTakeTime.setText(MyDateUtils.formatDateCustom(model.getActualTakeTime(), timetype));
        actualSendTime.setText(MyDateUtils.formatDateCustom(model.getActualSendTime(), timetype));
    }

    /**
     * 是否显示取衣按钮 与返洗按钮
     *
     * @param model
     */
    private void isShowTakeClothingBtn(List<QuiryDetailBean.ProductListBean> model) {
        if (CheckUtils.isEmpty(model))return;
        int enableSignCount = 0;
        int checkCount = 0;
        int stockReworkCount = 0;
        int enableRefundCount = 0;
        orderProIds="";
        StringBuffer mStringBuffer = new StringBuffer();
        for (QuiryDetailBean.ProductListBean productListBean : model) {
            /*衣物*/
            if (productListBean.isCheck()) {
                checkCount = checkCount + 1;
                if (productListBean.isEnableSign()) {/*签收数*/
                    enableSignCount = enableSignCount + 1;
                }
                if (productListBean.isEnableStockRework()) {/*返工数*/
                    stockReworkCount = stockReworkCount + 1;
                }

                if (productListBean.isEnableRefund()) {/*可退款数*/
                    enableRefundCount = enableRefundCount + 1;
                    mStringBuffer.append(productListBean.getId()).append(",");

                }




            }

        }


        if (mStringBuffer.length()!=0){
            orderProIds = mStringBuffer.deleteCharAt(mStringBuffer.length() - 1).toString();
        }

        if (checkCount == 0) {
            ordersDetailPickClothing.setVisibility(View.GONE);
            ordersDetailBackToWash.setVisibility(View.GONE);
            reashingBtn.setVisibility(View.GONE);
        } else {
            ordersDetailPickClothing.setVisibility(checkCount == enableSignCount ? View.VISIBLE : View.GONE);
            reashingBtn.setVisibility(checkCount == stockReworkCount ? View.VISIBLE : View.GONE);
            ordersDetailBackToWash.setVisibility(checkCount == enableRefundCount ? View.VISIBLE : View.GONE);

        }


    }


    /**
     * 交易方式
     *
     * @param mQuerypayData
     */
    @Override
    public void queryPayData(List<QueryPaBean> mQuerypayData) {
        this.mQuerypayData= (ArrayList<QueryPaBean>) mQuerypayData;
        if (!CheckUtils.isEmpty(mQuerypayData)) {
            StringBuffer mStringBuffer = new StringBuffer();
            for (int i = 0; i < mQuerypayData.size(); i++) {
                if (i != mQuerypayData.size() - 1) {
                    mStringBuffer.append(mQuerypayData.get(i).getPayMethodText() + "/");
                } else {
                    mStringBuffer.append(mQuerypayData.get(i).getPayMethodText());
                }
            }
            payMethodText.setText(mStringBuffer.toString());
            payTime.setText(MyDateUtils.formatDataTime(mQuerypayData.get(0).getTradeTime()));
        }


    }

    @Override
    public void allmarKprintSucceed(AllMarkprintBean mAllMarkprintBean) {

            PrinterHelper.getInstance().printAllWashings(mAllMarkprintBean);

    }


    @Override
    protected boolean useEventBus() {
        return true;
    }


    @Subscribe
    public void onEvent(AppEvent event) {

        switch (event.getMessage()) {
            case movebatch:
                String moveId = (String) event.getData();
                if (!CheckUtils.isEmpty(moveId) && !CheckUtils.isEmpty(moveproductIds))
                    mvpPresenter.BatchInReladd(_mActivity, moveId, moveproductIds);
                break;

        }

    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Subscribe
    public void onEvent(PayEvent event) {
        switch (event.getMessage()) {
            case PAY_SUCCEED:
                gatheringBtn.setVisibility(View.GONE);
                mvpPresenter.qrderQuiryDetailsData(_mActivity, mOrderId);
                mvpPresenter.queryPayList(mOrderId);
                break;
            case sendMode:
                SendModeBean mSendModeBeans = (SendModeBean) event.getData();
                mvpPresenter.updateSendMode(_mActivity, mOrderId, mSendModeBeans.getVal(), mSendModeBeans.getShowText());

                break;
            case returnWash:
                mvpPresenter.stockReworkBatch(moveproductIds);


                break;


        }

    }


    @Override
    public void loadPayStatus(PayInfoBean mPayInfoBean) {
        if (mPayInfoBean.getPayStatus()) {
            start(GatheringFragment.newInstance(mOrderId, "返回订单详情"), SINGLETASK);
        } else {
            T.show("您已付过款");

        }
    }


    @Override
    public void orderStatusData(List<OrderStateBean> mOrderStatusData) {

        if (!CheckUtils.isEmpty(mOrderStatusData)) {
            if (mOrderStatusData.get(3).isCheck()) {
                imageState.setImageResource(R.drawable.order_sign);
            }
        }
        mOrdersStateAdapter.setDatas(mOrderStatusData);


    }

    @Override
    public void loadFail(String message) {
        T.show(message);
    }


    @OnClick({marking_btn, R.id.back, gathering_btn, R.id.orders_detail_pick_clothing, R.id.sign_btn, R.id.accomplish_btn, R.id.sendModeText,
            R.id.printers_btn, R.id.reashing_btn, R.id.cancellation_btn, R.id.orders_detail_back_to_wash, R.id.refund_btn,
            R.id.refund_record_layout,R.id.transNo_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case  R.id.transNo_btn: /*录工厂运单号*/
                if (CheckUtils.isNull(mQuiryDetailBean))return;
                TansNoDialogFragment.createBuilder(getChildFragmentManager())
                        .title(getString(R.string.waybill_number))
                        .tansNo(mQuiryDetailBean.getFactoryTransNo())
                        .mOnDialogSureClickListener(mOnDialogTansNoClickListener)
                        .show();
                     break;
            case  R.id.refund_record_layout:/*退款记录*/
                if (CheckUtils.isNull(mQuiryDetailBean))return;
                /*退款状态 0.未退款 1.已退款 2.部分退款*/
                if (mQuiryDetailBean.getRefundPrice()>0){
                    mvpPresenter.tradeOrderRefund(_mActivity,mOrderId);
                }

                break;
            case R.id.refund_btn:/*订单退款*/
                if (!CheckUtils.isNull(mQuiryDetailBean))
                    isOrederRefund=true;
                    showBackWashDialog(mOrederRefundListener, isOrederRefund);



                break;
            case R.id.orders_detail_back_to_wash: /*退洗*/

                if (!CheckUtils.isNull(mQuiryDetailBean))
                    isOrederRefund=false;
                    showBackWashDialog(mClothingRefundListener,isOrederRefund);
                break;

            case R.id.cancellation_btn:
                CrippledDialogFragment mCrippledDialog = new CrippledDialogFragment();
                mCrippledDialog.setOnSureClickListener(mDialogListener);
                mCrippledDialog.show(getChildFragmentManager(), CrippledDialogFragment.class.getName());
                break;

            case R.id.reashing_btn:/*返洗*/
                if (CheckUtils.isEmpty(mAdapter.getDatas()))return;
                StringBuffer mStringBuffer1 = new StringBuffer();
                List<QuiryDetailBean.ProductListBean> poiIData = mAdapter.getDatas();
                for (QuiryDetailBean.ProductListBean item : poiIData) {
                    if (item.isCheck()) {

                        mStringBuffer1.append(item.getId()).append(",");

                    }

                }
                if (mStringBuffer1.length() == 0) return;
                moveproductIds = mStringBuffer1.deleteCharAt(mStringBuffer1.length() - 1).toString();
                mInquiryDialog = InquiryDialogFragment.newInstance("是否确认返洗");
                mInquiryDialog.show(getChildFragmentManager(), InquiryDialogFragment.class.getName());

                break;
            case marking_btn:

                if (CheckUsbDeviceUtils.isWashprinter() && !CheckUtils.isEmpty(mOrderId)) {/*水洗*/
                    mvpPresenter.allprintWash(_mActivity, mOrderId);
                }

                break;

            case R.id.printers_btn:

                if (CheckUtils.isMIUIDevices()){
                    mvpPresenter.printReceipt(_mActivity, mOrderId);
                }else if (CheckUsbDeviceUtils.isReceipt()) {/*小票*/
                    mvpPresenter.printReceipt(_mActivity, mOrderId);

                }

                break;

            case R.id.sendModeText:  /*送件方式*/
                if (isEnableChangeSendMode) {
                    if (CheckUtils.isNull(mSendModeBean)) {
                        mvpPresenter.sendMode(_mActivity);
                    } else {
                        showSendModeDialog(mSendModeBean);
                    }


                }


                break;

            case R.id.back:
                finish();
                break;
            case R.id.sign_btn:/*签收*/

                mvpPresenter.orderInfoSign(_mActivity, mOrderId);
                break;
            case R.id.accomplish_btn:/*完成按钮*/
                mvpPresenter.orderInfoCompleteid(_mActivity, mOrderId);
                break;
            case gathering_btn:/*收款按钮*/
                mvpPresenter.queryPayStatus(mOrderId);


                break;
            case R.id.orders_detail_pick_clothing:/*取衣*/
                if (CheckUtils.isEmpty(mAdapter.getDatas())) return;
                takeClogthData.clear();
                StringBuffer mStringBuffer = new StringBuffer();
                for (int i = 0; i < mAdapter.getDatas().size(); i++) {
                    QuiryDetailBean.ProductListBean mitem = mAdapter.getItem(i);
                    if (mitem.isCheck()) {
                        takeClogthData.add(mAdapter.getItem(i));
                        mStringBuffer.append(mAdapter.getItem(i).getId() + ",");
                    }

                }
                String ids = mStringBuffer.toString();
                if (CheckUtils.isEmpty(ids)) return;
                ids = mStringBuffer.toString().substring(0, ids.length());
                mvpPresenter.productSign(_mActivity, ids);


                break;

        }
    }


    /**
     *  未付款的退款方式对话框
     * @param mClothingRefundListener
     * @param isOrderRefund
     */
    private void showBackWashDialog(OnDialogSureClickListener mClothingRefundListener,boolean  isOrderRefund) {
        if (mQuiryDetailBean.getPayStatus()){

            if (!CheckUtils.isNull(mQuerypayData)){
                if (!CheckUtils.isNull(mRefundMethodBean)){
              RefundPayDialogFragment mBackWashDialog = RefundPayDialogFragment.newInstance(mQuiryDetailBean,mQuerypayData,mRefundMethodBean,isOrderRefund);
                 mBackWashDialog.setOnSureClickListener(mClothingRefundListener);
               mBackWashDialog.show(getChildFragmentManager(), BackWashDialogFragment.class.getName());
                }else{
                    mvpPresenter.refundMethodList();
                }

            }


        }else{
            BackWashDialogFragment mBackWashDialog = BackWashDialogFragment.newInstance(mQuiryDetailBean,isOrderRefund);
            mBackWashDialog.setOnSureClickListener(mClothingRefundListener);
            mBackWashDialog.show(getChildFragmentManager(), BackWashDialogFragment.class.getName());
        }

    }




    /**
     * 工厂运单号
     */
    private OnDialogSureClickListener mOnDialogTansNoClickListener = new OnDialogSureClickListener() {


        @Override
        public void onSureItemClick(Object message) {
            mvpPresenter.updateFactoryTransNo(mOrderId, (String) message);

        }
    };
    /**
     * 衣物退款
     */
    private OnDialogSureClickListener mClothingRefundListener = new OnDialogSureClickListener() {
        @Override
        public void onSureItemClick(Object message) {
            HashMap  mHashMap=(HashMap)message;
            mvpPresenter.clothingRefund(_mActivity, mOrderId,(String) mHashMap.get(ARG_PARAM1), orderProIds,(String)mHashMap.get(ARG_PARAM2),(String) mHashMap.get(ARG_PARAM3));

        }
    };
    /**
     * 订单退款
     */
    private OnDialogSureClickListener mOrederRefundListener = new OnDialogSureClickListener() {
        @Override
        public void onSureItemClick(Object message) {
            HashMap  mHashMap=(HashMap)message;

            mvpPresenter.orderRefund(_mActivity, mOrderId,(String) mHashMap.get(ARG_PARAM1),(String)mHashMap.get(ARG_PARAM2),(String) mHashMap.get(ARG_PARAM3));

        }
    };

    private OnDialogSureClickListener mDialogListener = new OnDialogSureClickListener() {
        @Override
        public void onSureItemClick(Object message) {
            mvpPresenter.orderInfoDestroy(_mActivity, mOrderId, (String) message);

        }
    };


    /**
     * 单件取衣
     */
    @Override
    public void takesClothesSuccess(String msg) {
        refreshData();
        T.show(msg);
    }

    /**
     * 订单签收成功
     *
     * @param msg
     */
    @Override
    public void loadSignSuccess(String msg) {
        T.show(msg);
        signBtn.setVisibility(View.GONE);
        accomplishBtn.setVisibility(View.VISIBLE);
        refreshData();


    }

    /**
     * 完成订单
     *
     * @param msg
     */
    @Override
    public void loadCompleteSuccess(String msg) {
        T.show(msg);
        accomplishBtn.setVisibility(View.GONE);
        refreshData();


    }

    /**
     * 打印小票
     */
    @Override
    public void loadReceipt(ReceiptBean mReceiptBean) {
        if (CheckUtils.isMIUIDevices()) {
            PrintMiuiHelper.receiptReceipt(MainActivity.getPrintService(),mReceiptBean );
        }else{
            GpDevice mDevice = new GpDevice();
            PrinterReceipt.getInstance().printGp80(mReceiptBean, mDevice);

        }


    }

    /**
     * 送件方式
     *
     * @param mSendModeBean
     */
    @Override
    public void SendModeData(ArrayList<SendModeBean> mSendModeBean) {
        this.mSendModeBean = mSendModeBean;
        showSendModeDialog(mSendModeBean);

    }


    /**
     * 修改送件模式对话框
     */
    private void showSendModeDialog(ArrayList<SendModeBean> mSendModeBean) {
        String strsendModeText = getText(sendModeText);
        for (SendModeBean sendModeBean : mSendModeBean) {
            if (strsendModeText.equals(sendModeBean.getShowText())) {
                sendModeBean.setCheck(true);
            } else {
                sendModeBean.setCheck(false);
            }
        }
        SendModeDialogFragment mSendModeDialog = SendModeDialogFragment.newInstance(mSendModeBean, "");
        mSendModeDialog.show(getChildFragmentManager(), SendModeDialogFragment.class.getName());
    }

    @Override
    public void updateSendMode(String msg, String updateMsg) {
        T.show(msg);
        sendModeText.setText(updateMsg);

    }

    /**
     * 退洗成功
     */
    @Override
    public void retreatSuccess() {
        //    mvpPresenter.orderStatusprogress(mOrderId);
    }

    /**
     * 提交返工审核
     */
    @Override
    public void stockReworkBatch() {
        mvpPresenter.qrderQuiryDetailsData(_mActivity, mOrderId);
        BatchDialogFragment mMoveBatchDialog = new BatchDialogFragment();
        Bundle mBundle = new Bundle();
        mBundle.putString(ARG_PARAM1, resources.getString(R.string.enter_number));
        mBundle.putString(ARG_PARAM2, "");
        mMoveBatchDialog.setArguments(mBundle);
        mMoveBatchDialog.show(getChildFragmentManager(), BatchDialogFragment.class.getName());

    }

    /**
     * 衣物详情
     *
     * @param mClothginQuiryBean
     */
    @Override
    public void clothingDetailsSuccess(ClothginQuiryBean mClothginQuiryBean) {
        start(ClothingDetailsFragment.newInstance(mClothginQuiryBean), SINGLETASK);
    }

    /**
     * 订单作废
     *
     * @param msg
     */
    @Override
    public void loadOrderInfoDestroy(String msg) {
        mvpPresenter.qrderQuiryDetailsData(_mActivity, mOrderId);
    }


    /**
     *
     * @param mRefundRecordBean 退款记录
     * @param mAuditRecordBean  审核记录
     */
    @Override
    public void refundRecordSuceed(ArrayList<RefundRecordBean.ListBean>  mRefundRecordBean,ArrayList<RefundRecordBean.ListBean>    mAuditRecordBean ) {
        if (CheckUtils.isNull(mQuiryDetailBean))return;
        if (CheckUtils.isEmpty(mRefundRecordBean)&&CheckUtils.isEmpty(mAuditRecordBean)){
            T.show("无退款记录");
            return;
        }
        RefundRecordDialogFragment mRefundRecordDialog = RefundRecordDialogFragment.newInstance(mRefundRecordBean,mAuditRecordBean,mQuiryDetailBean.getOrderNo());
        mRefundRecordDialog.show(getChildFragmentManager(), RefundRecordDialogFragment.class.getName());
    }


    /**
     * 退款成功
     * @param hide
     */
    @Override
    public void refundSucceed(String hide) {
        if (CheckUtils.isEmpty(hide))return;
        InquiryDialogFragment mInquiryDialog = InquiryDialogFragment.newInstance(hide,true);
        mInquiryDialog.show(getChildFragmentManager(),InquiryDialogFragment.class.getName());
        mvpPresenter.qrderQuiryDetailsData(_mActivity, mOrderId);


    }


    /**
     * 添加修改工厂运单号
     * @param factoryNo
     */
    @Override
    public void updateFactorySucceed(String factoryNo) {
                factoryTransNo.setText(getString(R.string.Factory_tracking_number)+factoryNo);
                mQuiryDetailBean.setFactoryTransNo(factoryNo);
                transNoBtn.setText(R.string.modified_number);

        if (getPreFragment() instanceof OrderManageFragment){

            ((OrderManageFragment) getPreFragment()).loadFinish=false;
        }


    }

    /**
     *返回退款方式
     * @param mRefundMethodBean
     */
    @Override
    public void refundMethodSucceed(ArrayList<RefundMethodBean> mRefundMethodBean) {
        this.mRefundMethodBean=mRefundMethodBean;
        if (isOrederRefund){
            showBackWashDialog(mOrederRefundListener, isOrederRefund);
        }else{
            showBackWashDialog(mClothingRefundListener,isOrederRefund);
        }







    }


}
